package com.disktalk.dao;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Repository;

import com.disktalk.entry.GroupUser;

@Repository
public class GroupUserDao {
	@Resource
	private JdbcTemplate jdbcTemplate; 
	public GroupUserDao(JdbcTemplate jdbcTemplate) {
		super();
		this.jdbcTemplate = jdbcTemplate;
	}
	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {  
        this.jdbcTemplate = jdbcTemplate;  
    }

	public void addGroupUser(GroupUser groupUser) {   
        String sql = "insert into groupUser(groupName,userName) "  
                    + "values (?,?)"; 
        System.out.println("DAO"+groupUser);
        Object[] params = {groupUser.getGroupName(),groupUser.getUserName()};    
        this.jdbcTemplate.update(sql, params);
	}
	public void delGroupUser(GroupUser groupUser) {
		try {
			String sql = "delete from groupUser where groupName=? and userName=?";
			Object[] params = {groupUser.getGroupName(),groupUser.getUserName()};
			this.jdbcTemplate.update(sql, params);
		} catch (DataAccessException e) {
			e.printStackTrace();
		}
	}
	public boolean find(GroupUser groupUser){
		String sql = "select * from groupUser where groupName=? and userName=?";
		SqlRowSet rs; 
		try {
			Object[] params = {groupUser.getGroupName(),groupUser.getUserName()};
			rs = this.jdbcTemplate.queryForRowSet(sql,params);
			while(rs.next()){  
				return true;
			}  
		} catch (DataAccessException e) {
			e.printStackTrace();
		}
		return false;
	}
	public List<String> findByUserName(String userName){
		String sql = "select * from groupUser where userName=?";
		SqlRowSet rs = null; 
		List<String> groupNames = new ArrayList<String>();
		try {
			Object[] params = {userName};
			rs = this.jdbcTemplate.queryForRowSet(sql,params);
			while(rs.next()){  
				groupNames.add(rs.getString(1));
			}  
		} catch (DataAccessException e) {
			e.printStackTrace();
		}
		return groupNames;
	}
	public List<String> findByGroupName(String groupName){
		String sql = "select * from groupUser where groupName=?";
		SqlRowSet rs = null; 
		List<String> userNames = new ArrayList<String>();
		try {
			Object[] params = {groupName};
			rs = this.jdbcTemplate.queryForRowSet(sql,params);
			while(rs.next()){  
				userNames.add(rs.getString(1));
			}  
		} catch (DataAccessException e) {
			e.printStackTrace();
		}
		return userNames;
	}
    
}
